package org.server.http.core;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Iterator;
import java.util.Map.Entry;

import org.server.http.conf.ServerConfig;

/**
 * 创建响应头
 * 
 * @author Admin
 * 
 */
public class BuilderHttpResponseHeader {
	// 响应头输出流
	private ByteArrayOutputStream headerOutputStream;
	// 响应对象
	private HttpResponse response;
	// 编码类型
	private final static String CHARSET = "utf-8";

	/**
	 * 准备创建响应头
	 * 
	 * @param response
	 */
	public BuilderHttpResponseHeader(HttpResponse res) {
		headerOutputStream = new ByteArrayOutputStream();
		response = res;
	}

	/**
	 * 生成响应头
	 * 
	 * @throws UnsupportedEncodingException
	 * @throws IOException
	 */
	public ByteArrayOutputStream responseHeaderStream() throws UnsupportedEncodingException, IOException {
		// 添加响应码
		StringBuilder res_status = new StringBuilder();
		res_status.append("HTTP/1.1 ");
		res_status.append(response.getStatus());
		res_status.append(" OK");
		addHeader(res_status.toString());
		// 缓存控制
		addHeader("Cache-Control", "must-revalidate, no-cache, private");
		// 添加响应类型
		if (response.getContentType() != null) {
			StringBuilder res_type = new StringBuilder();
			// 不需要添加字符编码
			res_type.append(response.getContentType());
			res_type.append(";");
			if (response.getCharset() != null) {
				// 添加字符编码类型
				res_type.append("charset=");
				res_type.append(response.getCharset());
			}
			addHeader("Content-Type", res_type.toString());
		}
		// 尝试添加其它可能存在的响应头
		// 禁止缓存
		addHeader("Pragma", "No-cache");
		// 写入页面时间
		addHeader("Date", new Date().toString());
		// 尝试写入其它可能存在的响应头
		if (response.getHeader() != null) {
			Iterator<Entry<String, String>> it = response.getHeader().entrySet().iterator();
			// 遍历可能存在的键值对
			while (it.hasNext()) {
				Entry<String, String> e = it.next();
				// 写入
				addHeader(e.getKey(), e.getValue());
			}
		}
		if (response.getStatus() == 200) {
			// 写入数据长度
			addHeader("Content-Length", String.valueOf(response.getContentLength()));
		}
		if (response.getSendredirectURI() != null) {
			// 执行重定向
			addHeader("Location", response.getSendredirectURI());
		}
		// 写入服务器名称
		addHeader("Server", ServerConfig.getServerName());
		// 写入换行，准备写入正文
		addHeader("");
		// 刷新流
		headerOutputStream.flush();
		return headerOutputStream;
	}

	// 如果值不为空，尝试添加需要输出的响应头，
	private void addHeader(String name, String value) throws UnsupportedEncodingException, IOException {
		if (value == null) {
			return;
		}
		// 拼接响应头
		StringBuilder accum = new StringBuilder();
		accum.append(name);
		// 使用冒号加空格连接
		accum.append(": ");
		accum.append(value);
		// 写入
		addHeader(accum.toString());
	}

	// 添加响应头
	private void addHeader(String value) throws UnsupportedEncodingException, IOException {
		// 写入
		headerOutputStream.write(value.getBytes(CHARSET));
		headerOutputStream.write("\r\n".getBytes(CHARSET));
	}
}
